package de.titama.control;

import de.titama.model.Task;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;


/**
 *
 * Controller für das Template Main.fxml
 * 
 * @author Thomas Müller
 * 
 */


public class RootController implements Initializable {
    
    DBConnect dbcon = new DBConnect();      
    
    @FXML private TableView<Task> tasktable;
    @FXML private TreeView<String> TreeList;
    @FXML private TableColumn<Task, String> TaskName;
    @FXML private TableColumn<Task, String> TaskPrio;
    @FXML private TableColumn<Task, String> TaskCreated;
    @FXML private TableColumn<Task, String> TaskDue;
    @FXML private TableColumn<Task, String> TaskCategory;
    @FXML private TextField SearchField;
    @FXML private TaskController taskcon;

    ObservableList<Task> data = FXCollections.observableArrayList();  

    
    @Override
    public void initialize(URL url, ResourceBundle rb) {       
        getTasksFromDB();
        TaskName.setCellValueFactory(new PropertyValueFactory<Task,String>("name"));
        TaskPrio.setCellValueFactory(new PropertyValueFactory<Task,String>("priority"));
        TaskCreated.setCellValueFactory(new PropertyValueFactory<Task,String>("created"));
        TaskDue.setCellValueFactory(new PropertyValueFactory<Task,String>("due"));
        TaskCategory.setCellValueFactory(new PropertyValueFactory<Task,String>("category"));
        tasktable.setItems(data);         
        TreeInit();           
        
        
        tasktable.setOnMouseClicked(event -> {
            if (event.getClickCount() == 2 && !tasktable.getSelectionModel().getSelectedItem().getCreated().equals("") ) {  
                EditTask(new ActionEvent(event.getSource(), TreeList));                
            }
    });
           
        TreeList.setOnMouseClicked(event -> {
            if (event.getClickCount() == 1 && !TreeList.getSelectionModel().getSelectedItem().getValue().equals("")) {  
                if(TreeList.getSelectionModel().getSelectedItem().getParent().getValue().equals("Aufgaben"))
                {
                   getTasksFromDB();
                   RefreshList();
                }
                else if(TreeList.getSelectionModel().getSelectedItem().getParent().getValue().equals("Priorität"))
                {
                    getTasksFromDB(TreeList.getSelectionModel().getSelectedItem().getValue(), 1);               
                }
                else if(TreeList.getSelectionModel().getSelectedItem().getParent().getValue().equals("Kategorie"))
                {
                    getTasksFromDB(TreeList.getSelectionModel().getSelectedItem().getValue(), 2);           
                }
            }
    });

        
        SearchField.setOnKeyPressed(event -> { 
                Search(SearchField.getText());
    });
 
    }
    
    
    /**
     * 
     * Öffnet das Template Categorys.fxml, über das sich die Kategorien bearbeiten lassen
     * 
     * @param event 
     */
    
    
    @FXML
    public void ShowCategorys(ActionEvent event) {
        Parent root;
        
        try 
        {
            root = FXMLLoader.load(getClass().getResource("/de/titama/view/Categorys.fxml"));
            Stage stage = new Stage();
            
            stage.setTitle("Kategorien verwalten");
            stage.setScene(new Scene(root, 355, 282));
            stage.setResizable(false);
            stage.show();


        } catch (IOException exe) {
            
            
        }
    }
    
    /**
     * 
     * Öffnet ein Fenster, über das eine neue Aufgabe angelegt werden kann.
     * 
     * @param event 
     */
      
    @FXML
    public void NewTask(ActionEvent event) {
        Parent root;
        
        try 
        {
            root = FXMLLoader.load(getClass().getResource("/de/titama/view/Task.fxml"));
            Stage stage = new Stage();
            
            stage.setTitle("Neue Aufgabe");
            stage.setScene(new Scene(root, 300, 400));
            stage.setResizable(false);
            stage.show();
        } 
        catch (IOException exe) {
            
        }
    }
    
    /**
     * 
     * Öffnet ein Fenster, über das sich die ausgewählte Aufgabe bearbeiten lässt.
     * 
     * @param event 
     */
    
    @FXML
    public void EditTask(ActionEvent event) {
        
       if(!tasktable.getSelectionModel().getSelectedItem().getCreated().equals(""))
       {
        Parent root;
       
        String tname = tasktable.getSelectionModel().getSelectedItem().getName();
        String tcat = tasktable.getSelectionModel().getSelectedItem().getCategory();
        String tprio = tasktable.getSelectionModel().getSelectedItem().getPriority();
        String tdue = tasktable.getSelectionModel().getSelectedItem().getDue();
        String tnotes = dbcon.getNotes(tname);
       
        
            try 
            {        
                FXMLLoader loader = new FXMLLoader();
                root =  loader.load(getClass().getResource("/de/titama/view/Task.fxml").openStream());
                taskcon = loader.getController();
        
                Stage stage = new Stage();
            
                stage.setTitle("Aufgabe bearbeiten");
                stage.setScene(new Scene(root, 300, 400));
                stage.setResizable(false);
                stage.show();             
            
                taskcon.SetData(tname,tcat,tprio,tdue,tnotes);

            } catch (IOException exe) {
            }
       }
       else
       {
           System.out.println("blub");
       }
    }
    
    
    /**
     * 
     *  Listet alle Aufgaben, die den übergebenen Suchbegriff beinhalten.
     * 
     * @param value     Suchbegriff
     */
    
    public void Search(String value)
    {                
        data.clear();
       
        
        for(String[] s : dbcon.getTasks())
        {
            if(s[0].contains(value))
            {
            Task t = new Task(s[0],s[1],s[2],s[3],s[4]);
            data.add(t);                            
            
            }
        }       
        tasktable.setItems(data);
    }
  
    
    /**
     * 
     * Öffnet das Template Info.fxml, welches Informationen zur Software enthält
     * 
     * @param event 
     */
    
    @FXML
    public void ShowInfo(ActionEvent event) {
        Parent root;
        
        try 
        {
            root = FXMLLoader.load(getClass().getResource("/de/titama/view/Info.fxml"));
            Stage stage = new Stage();
            
            stage.setTitle("Über Titama");
            stage.setScene(new Scene(root, 430, 320));
            stage.setResizable(false);
            stage.show();


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    
    /**
     * 
     * Holt alle Aufgaben aus der Datenbank und fügt diese der Liste "data" hinzu
     * 
     */
    
    public void getTasksFromDB()
    {
        data.clear();
        for(String[] s : dbcon.getTasks())
        {
            Task t = new Task(s[0],s[1],s[2],s[3],s[4]);
            data.add(t);
            
        }  
        
    }      
    

    /**
     * 
     * 
     * 
     * 
     * @param value
     * @param c 
     */
    public void getTasksFromDB(String value, int c)
    {
        
        data.clear();
       
        
        for(String[] s : dbcon.getTasks())
        {
            System.out.println(value.contains(s[4]));
            
        switch (c) {
            
            case 1:     if(value.contains(s[1]))
                        {
                            Task t = new Task(s[0],s[1],s[2],s[3],s[4]);
                            data.add(t);                            
                            System.out.println("true");
                        }
                        break;
                
            case 2:     if(value.contains(s[4]))
                        {
                            Task t = new Task(s[0],s[1],s[2],s[3],s[4]);
                            data.add(t);
                        }
                        break;
        
        }            
        }
        
        tasktable.setItems(data);
        
    }  

    
    @FXML
    public void Exit(ActionEvent e)
    {
        System.exit(0);
    }
    
    @FXML
    public void Delete(ActionEvent e)
    {
        dbcon.deleteTask(tasktable.getSelectionModel().getSelectedItem().getName());
        RefreshList();
     
    }
    
    public boolean RefreshList()
    {
        boolean refresh = false;
        try
        {
            data.clear();        
            getTasksFromDB();        
            tasktable.setItems(data);
            TreeInit();
            refresh = true;
        }
        catch(Exception exe)
        {
            exe.printStackTrace();
        }
        return refresh;
        
    }
        
    public void TreeInit()
    {
      TreeItem<String> PrioTree = new TreeItem<>("Priorität");
      PrioTree.setExpanded(true);
      PrioTree.getChildren().addAll(new TreeItem<>("Niedrig ("+dbcon.PrioCount("Niedrig")+")"),new TreeItem<>("Normal ("+dbcon.PrioCount("Normal")+")"), new TreeItem<>("Hoch ("+dbcon.PrioCount("Hoch")+")"),new TreeItem<>(""));
      
      TreeItem<String> CatTree = new TreeItem<>("Kategorie");
      CatTree.setExpanded(true);
      
      for(String s: dbcon.getCategorys())
      {
          CatTree.getChildren().add(new TreeItem<>(s + " (" +dbcon.CatCount(s) +")"));     
      }
      
       TreeItem<String> All = new TreeItem<>("Aufgaben");
       All.setExpanded(true);
       All.getChildren().addAll(new TreeItem<>("Alle (" +dbcon.TaskCount() +")"),new TreeItem<>(""));
    
        TreeItem<String> Root = new TreeItem<>();
        Root.getChildren().addAll(All,PrioTree, CatTree);
        TreeList.setRoot(Root);
        TreeList.setShowRoot(false);
    }
    

    
    


}
